package com.holly.unit.deform.modular.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.holly.unit.core.pojo.response.ResponseData;
import com.holly.unit.core.pojo.response.SuccessResponseData;
import com.holly.unit.db.api.pojo.druid.DruidProperties;
import com.holly.unit.deform.api.DeformBaseInfoApi;
import com.holly.unit.deform.api.pojo.base.DesignFormDTO;
import com.holly.unit.deform.api.pojo.online.pojo.ColumnInfo;
import com.holly.unit.deform.api.pojo.online.pojo.DesignFormDataPojo;
import com.holly.unit.deform.api.pojo.rsp.DeformResult;
import com.holly.unit.deform.entity.DesignFormData;
import com.holly.unit.deform.service.DeformDataService;
import com.holly.unit.deform.util.DatabaseDeFormUtil;
import com.holly.unit.deform.util.ExcelUtils;
import com.holly.unit.deform.util.JsonUtil;
import com.holly.unit.office.api.OfficeExcelApi;
import com.holly.unit.office.api.pojo.report.ExcelExportData;
import com.holly.unit.query.api.QueryApi;
import com.holly.unit.scanner.api.annotation.ApiResource;
import com.holly.unit.scanner.api.annotation.GetResource;
import com.holly.unit.scanner.api.annotation.PostResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 类描述: 表单设计器导出控制器
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/14 15:08
 */
@RestController
@ApiResource(name = "表单设计器导出")
@Api(tags = "表单设计器导出")
@Slf4j
public class DeformExportExcelController {

    @Resource
    private DeformDataService dataService;

    @Resource
    private DeformBaseInfoApi base;

    @Resource
    private QueryApi queryApi;

    @Resource
    private OfficeExcelApi officeExcelApi;

    @Resource
    private DruidProperties druidProperties;

    /**
     * 导出 Excel
     * @param desformCode
     * @param request
     * @param response
     */
    @GetMapping(value = "/exportXls/{desformCode}")
    @GetResource(name = "表单数据导出", path = "/exportXls/{desformCode}", requiredPermission = false , requiredLogin = false)
    @ApiOperation(value = "表单数据导出" ,notes = "表单数据导出")
    public void exportXls(DesignFormData designFormData,
                          @PathVariable("desformCode") String desformCode,
                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                          @RequestParam(name = "tableName") String tableName,
                          @RequestParam(name = "selectionIds", required = false) String selectionIds,
                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                          @RequestParam(name = "superQuery", required = false, defaultValue = "{}") String superQuery,
                          HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1. 查询表单信息
        DesignFormDTO designFormDTO = base.getByCode(desformCode);
        if (designFormDTO == null) {
            return;
        }
        /*DesignForm designForm = new DesignForm();
        BeanUtil.copyProperties(designFormDTO,designForm);
        // 组件列表
        List<DesformWidget> widgetList = DeformUtil.getDesformWidgetListByEntity(designForm);
        //2. 查询数据
        QueryWrapper<DesignFormData> queryWrapper = queryApi.initQueryWrapper(designFormData, request.getParameterMap());
        //选择行导出
        if(StrUtil.isNotEmpty(selectionIds)){
            queryWrapper.in("id",selectionIds.split(","));
        }
        String username = LoginContext.me().getLoginUser().getAccount();
        //设置为此值则查询所有数据
        pageSize = -521;
        if(superQuery!=null &&  StrUtil.isNotEmpty(superQuery)){
            superQuery = HtmlUtils.htmlUnescape(superQuery);
        }
        DeformResult<PageResult<DesignFormData>> designFormDataPageResult = dataService.queryPage(desformCode, pageNo, pageSize, queryWrapper, superQuery, username);
        List<DesignFormData> designFormDataParentList = new ArrayList<>();
        if (designFormDataPageResult.getResult() != null) {
            designFormDataParentList = designFormDataPageResult.getResult().getRows();
        }
        // 导出数据
        List<Map<String, Object>> designFormDataList = new ArrayList<>(designFormDataParentList.size());
        for (DesignFormData dataItem : designFormDataParentList) {
            String dataJSONString = dataItem.getDesformDataJson();
            if (StrUtil.isNotBlank(dataJSONString)) {
                designFormDataList.add(JSON.parseObject(dataJSONString).getInnerMap());
            }
        }
        //EXCEL导出数据转换器
        ConvertUtil.doConvertDataList(ConvertUtil.out, designFormDataList, widgetList);

        String desformDesignJson = designForm.getDesformDesignJson();
        JSONObject json = JSON.parseObject(desformDesignJson);
        JSONArray dataList = json.getJSONArray("list");
        String[] dataStrMap = new String[dataList.size()];
        List<List<String>> head = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++){
            dataStrMap[i] = dataList.getJSONObject(i).getString("model");
            List<String> headList = new ArrayList<>();
            headList.add(dataList.getJSONObject(i).getString("name"));
            head.add(headList);
        }*/
        //查询数据表字段 组装表头
        List<ColumnInfo> originalTableColumn = DatabaseDeFormUtil.findOriginalTableColumn(druidProperties, tableName);
        List<String> dataStrMap = new ArrayList<>();
        List<List<String>> head = new ArrayList<>();
        List re = Arrays.asList(JsonUtil.pageFilterFields.split(","));

        String query = HtmlUtils.htmlUnescape(superQuery);
        JSONObject superQueryJSON = JSONObject.parseObject(query);
        String field = superQueryJSON.getString("field");
        if(StrUtil.isNotEmpty(field)){
            String[] split = field.split(",");
            List reField = Arrays.asList(split);
            for (int i = 0; i < originalTableColumn.size(); i++){
                if (reField.contains(originalTableColumn.get(i).getFieldName()) && !re.contains(originalTableColumn.get(i).getFieldName())) {
                    dataStrMap.add(originalTableColumn.get(i).getFieldName());
                    List<String> headList = new ArrayList<>();
                    headList.add(originalTableColumn.get(i).getColComment());
                    head.add(headList);
                }
            }
        }
        //查询数据
        DesignFormDataPojo designFormDataPojo = new DesignFormDataPojo();
        designFormDataPojo.setTableName(tableName);
        designFormDataPojo.setSuperQuery(superQuery);
        designFormDataPojo.setPageSize( -521);
        designFormDataPojo.setPageNo(pageNo);
        DeformResult formData = dataService.queryFormDataList(designFormDataPojo);
        List<Map<String, Object>>  result = ( List<Map<String, Object>> )formData.getResult();
        ExcelExportData excelExportParam = new ExcelExportData();
        excelExportParam.setHead(head);
        excelExportParam.setDataStrMap(dataStrMap.toArray(new String[dataStrMap.size()]));
        excelExportParam.setDataList(result);
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLS);
        excelExportParam.setFileName(designFormDTO.getDesformName());
        excelExportParam.setResponse(response);
        officeExcelApi.dynamicExportDownload(excelExportParam);
    }

    /**
     * 导出 Excel
     * @param desformCode
     * @param request
     * @param response
     */
    @PostMapping(value = "/importExcel/{desformCode}")
    @PostResource(name = "表单数据导入", path = "/importExcel/{desformCode}", requiredPermission = false , requiredLogin = false)
    @ApiOperation(value = "表单数据导入" ,notes = "表单数据导入")
    public ResponseData importExcel(HttpServletRequest request, @PathVariable("desformCode") String desformCode) throws IOException {
        //1. 查询表单信息
        DesignFormDTO designFormDTO = base.getByCode(desformCode);
        //2. 获取上传文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //3. 遍历上传文件
        JSONArray data = new JSONArray();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取单个上传文件
            MultipartFile file = entity.getValue();
            JSONArray objects = ExcelUtils.readMultipartFile(file);
            //数组拼接
            data.addAll(objects);
        }
        //数据保存数据库
        List<Map<String,Object>> projectSiteList = (List<Map<String,Object>>) JSONArray.parse(data.toJSONString());
        dataService.addTableData(projectSiteList,designFormDTO.getCgformCode());
        return new SuccessResponseData() ;
    }

}
